/**
 * Copyright (C), 2018-2020, 龙腾出行
 * FileName: ExcelUtils
 * Author:   dpj
 * Date:     2020/8/5 16:18
 * Description: 导出工具类
 * History:
 * <author>          <time>          <version>          <desc>
 * dpj           16:18         1.0.0              描述
 */
package com.huangwenshuo.futurestarschoolmanagement.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Excel导出相关处理
 *
 * @author yb
 */
public class ExcelUtils<T> {

    public Class<T> clazz;

    public ExcelUtils(Class<T> clazz)
    {
        this.clazz = clazz;
    }
    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @param response
     */
    public  void exportExcel(List<T> list, HttpServletResponse response, String fileName) {
        ExcelWriter writer = ExcelUtil.getWriter();
        Field[] allFields = clazz.getDeclaredFields();// 得到所有定义字段
        List<Field> fields = new ArrayList<Field>();
        // 得到所有field并存放到一个list中.
        for (Field field : allFields) {
            if (field.isAnnotationPresent(Excel.class)) {
                fields.add(field);
            }
        }
        // 写入各个字段的列头名称
        for (int i = 0; i < fields.size(); i++) {
            Field field = fields.get(i);
            Excel attr = field.getAnnotation(Excel.class);
            if (StringUtils.isNotEmpty(attr.name())) {
                //自定义标题别名
                writer.addHeaderAlias(field.getName(), attr.name());
            }
        }
// 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list, true);
//out为OutputStream，需要写出到的目标流
//response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
//.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + "-jct.xls");
        response.setHeader("requset-type","file");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
// 关闭writer，释放内存
            writer.close();
//此处记得关闭输出Servlet流
            IoUtil.close(out);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}